package root.electronclass.electronclass.school.model

import androidx.lifecycle.*
import root.electronclass.electronclass.mvp.entity.NoticeData
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.school.rep.SchoolRepository
import root.electronclass.electronclass.mvp.entity.FirstCharTeacherDto
import root.electronclass.electronclass.mvp.entity.HonorList
import root.electronclass.electronclass.mvp.entity.RcHonor
import root.electronclass.electronclass.mvp.entity.RcHonorVo
import kotlinx.coroutines.launch

/**
 *@ClassName TODO
 *@Description TODO
 *@Author caofc
 *@Date 2023/3/31 23:25
 */
class SchoolNotificationModel : ViewModel() {
    private val _data = MediatorLiveData<Pair<Int, List<NoticeData>>>()
    val rcHonor = MediatorLiveData<List<RcHonor>>()
    val rcSHonor = MediatorLiveData<List<HonorList>?>()
    val listByFirstChar = MediatorLiveData<List<FirstCharTeacherDto>>()
    val data: LiveData<Pair<Int, List<NoticeData>>> = _data

    private val pageIndex = MutableLiveData(1)

    private var text: String = ""
    private var type: Int = 1//0-全部 1-近7天 2-近30天 3-一学期

    init {
        load(page = 1)
    }

    /**
     * 加载班级通知
     */
    fun load(type: Int = this.type, text: String = this.text, page: Int = (pageIndex.value ?: 1) + 1) {
        this.text = text
        this.type = type
        pageIndex.value = page
        loadData(type, text)
    }

    private fun loadData(type: Int, text: String) {
        viewModelScope.launch(CoroutineExceptionHandler() { pageIndex.value = ((pageIndex.value ?: 1) - 1).coerceAtLeast(1) }) {
            _data.value = pageIndex.value!! to SchoolRepository.getSchoolNotification(pageIndex.value!!, type, text)
            pageIndex.value = (pageIndex.value ?: 1) + 1
        }
    }

     fun editData(item: NoticeData) {
        viewModelScope.launch(CoroutineExceptionHandler()) {
            SchoolRepository.updateNotice(item)
        }
    }

    fun rcHonorList() {
        viewModelScope.launch(CoroutineExceptionHandler()) {
            rcHonor.postValue(SchoolRepository.rcHonorList().rows)
        }
    }

    fun getRcHonorList(type: Int) {
        viewModelScope.launch(CoroutineExceptionHandler()) {
            rcSHonor.postValue(SchoolRepository.getRcHonorList(RcHonorVo(type)).rows)
        }
    }

    fun listByFirstChar(option: String?) {
        viewModelScope.launch(CoroutineExceptionHandler()) {
            listByFirstChar.postValue(SchoolRepository.listByFirstChar(option).rows)
        }
    }



}